package com.bao.work;

import java.util.Arrays;

public class InnerClassTest04 {
    public static void main(String[] args) {
        MyArrayList list=new MyArrayList();
        list.add("狗大王");
        list.add("乌龟大王");
        list.add("猫王");

        list.remove(1);

        list.set(1,"大蛇丸");

        System.out.println("获取index为1的元素:\n"+list.get(1));

        Selector selector=list.select();
        System.out.println("打印所有元素:");
        while (selector.hasNext()){
            System.out.println(selector.next());
        }
        System.out.println("==================================");

    }
}
interface Selector{
    boolean hasNext();
    Object next();
}
interface Touchable{
    Selector select();
}
class MyArrayList implements Touchable{
    private Object[] all=new Object[2];
    private int total;

    public void add(Object element){
        //添加元素到当前容器中,all已满,扩容
        all[total++]=element;
        if(total==all.length){
            Object[] bll=new Object[all.length*2];
            System.arraycopy(all, 0, bll, 0, all.length);
            all=bll;
        }

    }
    public void remove(int index){
        if(index<0||index>total){
            System.out.println("没有这个元素");
        }else{
            all[index]=null;
            if (total - index >= 0) System.arraycopy(all, index + 1, all, index, total - index);
            all[--total]=null;
        }
    }
    public void set(int index,Object value){
        if(index<0||index>total){
            System.out.println("没有这个元素");
        }else{
            //替换元素
            all[index]=value;
        }
    }
    public Object get(int index){
        if(index<0||index>total){
            System.out.println("没有这个元素");
            return null;
        } else {
            return all[index];
        }
    }
    private class MySelector implements Selector{
        int cursor;

        @Override
        public boolean hasNext() {
            return cursor!=total;
        }

        @Override
        public Object next() {
            return all[cursor++];
        }
    }
    @Override
    public Selector select() {
        return new MySelector();
    }
}
